import Vue from 'vue'
import Router from 'vue-router'
import store from './store/index'
import createStoreModule from '@/widgets/xdh-nav-tabs/store'

const NAV_JSON = require('./nav.json')
const DEMO_STORE = 'demoTabs'


const LOAD_DOCS_MAP = {
  'guide': file => () => import('./docs/guide/' + file + '.md'),
  'element': file => () => import('./docs/element/' + file + '.md'),
  'widgets': file => () => import('./docs/widgets/' + file + '.md'),
  'libs': file => () => import('./docs/libs/' + file + '.md')
};

const loadDocs = function (category, path) {
  let file = path.replace('/' + category + '/', '')
  if (file) {
    return LOAD_DOCS_MAP[category](file);
  }
}

const sort = function (array) {
  return array.sort((a, b) => {
    let textA = a.text.toUpperCase(); // ignore upper and lowercase
    let textB = b.text.toUpperCase(); // ignore upper and lowercase
    if (textA < textB) {
      return -1;
    }
    if (textA > textB) {
      return 1;
    }
// names must be equal
    return 0;
  })
}

const getChildrenRoutes = function (category, array) {
  let routes = []
  if (['widgets', 'libs'].includes(category)) {
    sort(array)
  }
  array.forEach(item => {
    if (item.children) {
      let childrenRoutes = getChildrenRoutes(category, item.children)
      if (childrenRoutes && childrenRoutes.length > 0) {
        routes.push({
          path: item.path,
          redirect: childrenRoutes[0].path
        })
        routes = routes.concat(childrenRoutes)
      }
    } else {
      routes.push({
        path: item.path,
        component: item.vue ? () => import(`./components/${item.vue}.vue`) : loadDocs(category, item.path),
        name: item.text,
        meta: {tab: true}
      })
    }
  })
  return routes
}


// 注册导航tabs store模块
if (!store.state[DEMO_STORE]) {
  store.registerModule(DEMO_STORE, createStoreModule())
}

Vue.use(Router)

let routes = []
let categories = Object.keys(NAV_JSON)
categories.forEach(name => {
  routes = routes.concat(getChildrenRoutes(name, NAV_JSON[name]))
})


const router = new Router({
  routes: [
    {
      path: '/',
      redirect: 'guide/changelog',
      component: () => import('./components/layout.vue'),
      children: routes
    },
    {
      path: '/src/:url',
      component: () => import('./components/frame.vue')
    }
  ]
})

router.afterEach((to) => {
  if (to.meta.tab) {
    store.commit(`${DEMO_STORE}/push`, {
      tab: {
        label: to.name,
        name: to.path,
        closable: true
      }
    })
  } else {
    store.commit(`${DEMO_STORE}/clear`)
  }
})
export default router
